﻿using MiniFox;
using MiniFox.Caching;
using MiniFox.Components;
using MiniFox.Platform.Applications;
using MiniFox.Platform.Applications.Auth;
using MiniFox.Platform.File.Models;
using Platform.Core.Models;
using Platform.Core.Providers;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;

namespace Platform.Core.Services
{
    /// <summary>
    /// 
    /// </summary>
    public class WatermarkService : ApiServiceBase, IWatermarkService
    {
        public WatermarkService(SystemPrincipal principal) : base(principal)
        {

        }
        [AutoWired]
        protected IWatermarkProvider Provider { get; set; }
        Watermark _model;
        protected Watermark Model
        {
            get
            {
                if (_model == null)
                {
                    _model = Provider.LoadWatermarkModel();
                    var authClient = Principal;
                    _model.Text = authClient.Identity.Name;
                }
                return _model;
            }
        }
        /// <summary>
        /// 定义画布
        /// </summary>
        /// <returns></returns>
        protected virtual Image CreateCanvas()
        {
            int w = Model.CanvasWidth;
            int h = Model.CanvasHeight;
            return new Bitmap(w, h, PixelFormat.Format32bppArgb); //定义画布
        }

        protected virtual MemoryStream CreateWatermarkImage()
        {
            int w = Model.Width;
            int h = Model.Height;
            Image watermark = new Bitmap(w, h, PixelFormat.Format32bppArgb);
            var graphics = Graphics.FromImage(watermark);

            graphics.SmoothingMode = SmoothingMode.AntiAlias;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.CompositingQuality = CompositingQuality.HighQuality;
            graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;

            StringFormat format = StringFormat.GenericTypographic;
            format.FormatFlags = StringFormatFlags.NoWrap;
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;

            Brush brush = new SolidBrush(Model.FontColor);
            graphics.DrawString(Model.Text, Model.Font, brush, Model.TextRectangle, format);
            MemoryStream stream = new MemoryStream();
            watermark.Save(stream, ImageFormat.Png);
            return stream;
        }
        protected virtual byte[] DrawWatermark()
        {
            using (Image imageCanvas = CreateCanvas())//定义画布
            {
                Image watermark = null;
                Graphics graphics = null;

                try
                {
                    using (MemoryStream stream = CreateWatermarkImage())
                    {
                        watermark = Image.FromStream(stream);
                        graphics = Graphics.FromImage(imageCanvas);

                        graphics.CompositingQuality = CompositingQuality.HighQuality;
                        graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                        graphics.SmoothingMode = SmoothingMode.HighQuality;

                        Matrix matrix = graphics.Transform;
                        matrix.RotateAt(Model.RotateAngle, Model.RotatePoint);
                        graphics.Transform = matrix;

                        graphics.DrawImage(watermark, new RectangleF(Model.X, Model.Y, Model.Width, Model.Height));
                    }
                }
                catch
                {
                }
                finally
                {
                    if (watermark != null)
                    {
                        watermark.Dispose();
                    }
                    if (graphics != null)
                    {
                        graphics.Dispose();
                    }
                }
                using (MemoryStream stream = new MemoryStream())
                {
                    imageCanvas.Save(stream, ImageFormat.Png);
                    return stream.ToArray();
                }
            }
        }
        public virtual FileData CreateWatermark()
        {
            var key = $"watermark#{Principal.GlobalID}";
            var fileData = CacheService.GetCacheProvider("file").Get(key, () =>
            {
                return new FileData
                {
                    FileId = SequenceGUID.NewGUID(),
                    CreateTime = DateTime.Now,
                    Group = "watermark",
                    Data = DrawWatermark(),
                    FileName = $"{Principal.Name}.png",
                    ContentType = MiniFox.Resources.MimeTypes.Png,
                };
            });
            return fileData;
        }
    }
}
